package com.example.shop.merchant.interceptor;

import com.example.shop.common.api.ResponseResult;
import com.example.shop.common.api.ServiceStateCode;
import com.example.shop.common.enums.SessionAttributeKey;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource(name = "redisObjectMapper")
    ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if(session.getAttribute(SessionAttributeKey.NOW_LOGIN_MERCHANT.getKey())==null){
            ResponseResult<Object> auto = ResponseResult.auto(ServiceStateCode.LOGIN_AFTER_OPERATION, null);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().write(objectMapper.writeValueAsString(auto));
            return false;
        }
        /*如果拦截成功false，则后面的方法全都不会调用
           如果为true，代表流向下一个拦截器的preHandle处理。如果是最后一个则流向处理器类映射的方法处理，
           处理完后开始往回走，拦截器链顺序从尾到头调用postHandler方法，直到视图返回。即视图已经呈现在客户端了
           返回后也是重新从拦截器链尾到头调用afterCompletion方法
        * */
        return true;
    }
    //handler处理器执行之后，视图渲染之前。
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    //请求处理完成后，即呈现视图后，即响应已经提交。回调该方法，常用于适当的资源清理。
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
